from models import DB
from pkg.tools import now_timestamp
from pkg.tools.pinyin import get_pinyin


class Tag(DB.Model):
    # 定义表名
    __tablename__ = 'tag' # 定义表名
    # 定义列对象
    id = DB.Column(DB.Integer, primary_key=True)
    name = DB.Column(DB.String(64),  nullable=False)
    byname = DB.Column(DB.String(64), default=name,  nullable=False)
    created_on = DB.Column(DB.Integer, default=now_timestamp(), nullable=False)
    update_on = DB.Column(DB.Integer, default=created_on, nullable=False)
    # 设置外键[用于1查询多的情况]
    articles = DB.relationship("Article", backref="tag", lazy='dynamic')

    # repr()方法类似于django的__str__，用于打印模型对象时显示的字符串信息
    def __repr__(self):
        return 'Tag:%s'% self.name


def add(name, byname=None):
    t = Tag(name=name, byname=byname)

    DB.session.add(t)
    DB.session.commit()
    return f"添加TAG {name} 成功"

def add_in_pinyin(name):
    return add(name, get_pinyin(name))



def delete(id):
    t = Tag.query.get(id)
    if t == None:
        return f"错误: {id} 不存在"
    DB.session.delete(t)
    DB.session.commit()
    return f"成功删除TAG  {t.name} "



def update(id, name, byname=None):
    t = Tag.query.get(id)
    if t == None:
        return f"错误: {id} 不存在"
    old_name = t.name

    if byname != None:
        t.byname = byname
    t.name = name

    DB.session.commit()
    return f"{old_name} 修改成功"
    

def get(id):
    t = Tag.query.get(id)
    if t == None:
        return f"错误: {id} 不存在"
    return t

def get_all():
    ts = Tag.query.all()
    return ts

def count():
    return Tag.query.count()


def articles(id):
    t = Tag.query.get(id)
    return t.articles.all()

def is_exist(id):
    t = Tag.query.get(id)
    if t:
        return True
    return False